package com.ly.publish;

import com.ly.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer02 {
    public static void main(String[] args) {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = null;
        try {
            channel = connection.createChannel();
            //声明交换机
            channel.exchangeDeclare(Producer.FANOUT_EXCHAGE, BuiltinExchangeType.FANOUT);
            //声明队列
            channel.queueDeclare(Producer.FANOUT_QUEUE_2,false,false,false,null);
            //队列绑定交换机
            channel.queueBind(Producer.FANOUT_QUEUE_2,Producer.FANOUT_EXCHAGE,"");
            DefaultConsumer consumer = new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    /***
                     * consumerTag 消息者标签，在channel.basicConsume时候可以指定
                     * envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重 传标志 (收到消息失败后是否需要重新发送)
                     * properties 属性信息
                     * body 消息
                     */
                    System.out.println("路由key为:" + envelope.getRoutingKey());
                    //交换机
                    System.out.println("交换机为：" + envelope.getExchange());
                    //消息id
                    System.out.println("消息id为：" + envelope.getDeliveryTag());
                    //收到的消息
                    System.out.println("接收到的消息为：" + new String(body, "utf-8"));
                    System.out.println(consumerTag);
                }
            };
            channel.basicConsume(Producer.FANOUT_QUEUE_2,true,consumer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
